#
# EncoderViewItem.py
#
# This work is released under the GNU GPL, version 2 or later.
#
from qt import *
from kdeui import *
from Utils.human import *
from Utils.Paths import *
from TrackViewItemObject import *
import time

def _get(a,b):
	if a==None: return b
	return a

_encodingIcons = None
def encodingIcons(index):
	global _encodingIcons
	if _encodingIcons==None:
		_encodingIcons = [QPixmap(art("labelimporting0.png")),QPixmap(art("labelimporting1.png")),QPixmap(art("labelimporting2.png"))]
	return _encodingIcons[index]

_encodedIcon = None
def encodedIcon():
	global _encodedIcon
	if _encodedIcon==None:
		_encodedIcon = QPixmap(art("labelimported.png"))
	return _encodedIcon

class EncoderViewItem(KListViewItem):
	def __init__(self,container,track,index):
		QListViewItem.__init__(self,container)
		self._index = index
		self._track = track
		self.trackItem = LTrackViewItemObject(self)
		self.setDragEnabled(True)
		self.encodeTime = 0
		self.encodeIcon = -1
		self.loadTrackInfo()

	def die(self):
		pass
	
	def contentsMouseDoubleClickEvent(self,event):
		pass
	
	def key(self,column, ascending):
		try:
			if column==1: return self.trackKey
		except: pass
		return KListViewItem.key(self,column,ascending)

	def track(self):
		return self._track

	def trackID(self):
		return self._track.trackID

	def loadTrackInfo(self):
		self.trackKey = "%05d" % self._index
		self.setText(1,str(self._index))
		self.setText(2,_get(self._track.title,""))
		self.setText(3,humanDuration(self._track.totalTime))
		self.setText(4,_get(self._track.artist,""))
		self.setText(5,_get(self._track.album,""))
		self.setText(6,_get(self._track.genre,""))
		self.ripStatus(self._track,None)

	def contextMenu(self,pos,col):
		pass

	def changedAttribute(self,attribute,oldValue,newValue):
		#print "attribute",attribute,"from",oldValue,"to",newValue
		if attribute in ['trackNum','title','artist','album','playStatus','ripStatus']:
			if attribute!='playStatus':
				self.status = 'idle'
			self.loadTrackInfo()

	def ripStatus(self,track,status):
		#print track.ripStatus
		if track.ripStatus=='ripping':
			self.setNextEncodingIcon()
			return True
		elif track.ripStatus=='ripped':
			self.setEncodedIcon()
			return True
		self.setIdleIcon()
		return False

	def setIdleIcon(self):
		self.setPixmap(0,QPixmap())

	def setNextEncodingIcon(self):
		now = time.time()
		if now>self.encodeTime:
			self.encodeIcon = (self.encodeIcon+1) % 3
			self.setPixmap(0,encodingIcons(self.encodeIcon))
			self.encodeTime = now
	
	def setEncodedIcon(self):
		self.setPixmap(0,encodedIcon())
